import Taro, {Component} from "@tarojs/taro";
import {View, Switch, Input, Form, Button} from "@tarojs/components";
import {inject, observer} from '@tarojs/mobx'
import {getRuntime,isPhone} from '../../utils/common'
import {IStoreProps} from '../../store/Stores'

import '../mall/mall.less'
import PickerArea from "../../components/PickerArea";

// 我的，收货地址-编辑
interface IHomeProps extends IStoreProps {}

@inject("stores")
@observer
class AddressEdit extends Component<IHomeProps> {
  constructor(props) {
    super(props)
  }

  state = {
    allProvince:[],
    allCity:[],
    allDistract:[],
    provinceIndex: 0,
    cityIndex: 0,
    distractIndex: 0,
    area:null,
    areaInfo:null, // 详细地址
    editAddress: [],
    editId: 0,
    isDefaultAddress: false
  }

  componentWillMount(): void {
    Taro.setNavigationBarTitle({ title:'修改收货地址' })
    let id = this.$router.params.id
    if(!id){ getRuntime().navigateBack(); return }
    this.setState({
      editId: parseInt(id)
    })
    this.getEditAddress(id)
  }

  // 获取地址信息
  getEditAddress(id) {
    let allAddress = getRuntime().getStorage('userAddress')
    if(!allAddress){ getRuntime().navigateBack(); return }
    allAddress.map((item, index) => {
      if(item.id == id){
        let editAddress = allAddress[index]
        let tempArr = Array(2).fill(null)
        if(editAddress.receiverAddress.includes('@')){
           tempArr = editAddress.receiverAddress.split('@')
        }
        this.setState({
          editAddress,
          isDefaultAddress: editAddress['isDefault'],
          area: tempArr[0],
          areaInfo: tempArr[1],
        })
      }
    })
  }

  changeDefaultAddress() {
    this.setState({
      isDefaultAddress: !this.state.isDefaultAddress
    },() => {
      if(this.state.isDefaultAddress){
        this.setDefaultUserAddress()
      }else {
        // 取消默认地址
      }
    })
  }
  // 设置默认地址
  setDefaultUserAddress() {
    let { userStore } = this.props.stores
    let id = this.state.editId
    if(!id){getRuntime().showToast('参数错误，请重试~'); return}
    userStore.setDefaultUserAddress({
      id,
      callback: () => {
        getRuntime().showToast('设置默认地址成功~')
      }
    })
  }
  // 删除地址
  removeUserAddress(id: number) {
    let { userStore } = this.props.stores
    if(!id){getRuntime().showToast('参数错误，请重试~'); return}
    getRuntime().showModal('您确定要删除该地址吗?','',() => {
      userStore.removeUserAddress({
        id,
        callback: res => {
          getRuntime().showToast('删除地址成功~')
          setTimeout(() => {
            getRuntime().navigateBack()
          },2000)
        }
      })
    })
  }

  pickerArea(res) {
    this.setState({
      area: res.province.label+res.city.label+res.distract.label
    })
  }

  submit(e) {
    let { userStore } = this.props.stores
    let { area,isDefaultAddress } = this.state
    let {receiver,receiverPhone,addressInfo} = e.detail.value
    if(!receiver){ getRuntime().showToast('收货人姓名不能为空~'); return false}
    if(!receiverPhone){ getRuntime().showToast('收货人手机号码不能为空~'); return false }
    if(!isPhone(receiverPhone)){ getRuntime().showToast('收货人手机号码格式不正确~'); return false }
    if(!area){ getRuntime().showToast('请选择省市区信息~'); return false }
    if(!addressInfo){ getRuntime().showToast('请填写详细地址信息~'); return false }
    userStore.saveUserAddress({
      form: {
        receiver,
        receiverPhone,
        receiverAddress: area+'@'+addressInfo,
        postalCode: '',
        id: this.state.editId
      },
      callback: () => {
        getRuntime().showToast('保存地址成功~')
        setTimeout(() =>{
          getRuntime().navigateBack()
        },2000)
      }
    })
  }
  render() {
    let { editId,editAddress,isDefaultAddress,area,areaInfo } = this.state
    console.log(area)
    return (
      <View className='address-edit'>
        <Form onSubmit={this.submit.bind(this)}>
          <View className='from-wrap'>
            <View className='item-group'>
              <View className='input-group'>
                <View className='input-name'>收货人姓名</View>
                <Input className='from-input' name='receiver' value={editAddress.receiver} placeholder='请填写收货人姓名' placeholderStyle={{'font-size': '26px'}} />
              </View>

              <View className='input-group'>
                <View className='input-name'>手机号码</View>
                <Input className='from-input' name={'receiverPhone'} value={editAddress.receiverPhone} type={"number"} maxLength={11} placeholderClass='placeholder_class' placeholder='请填写手机号码'/>
              </View>

              <View className='input-group '>
                <View className='input-name'>省/市/区</View>
                <PickerArea onPicketArea={this.pickerArea.bind(this)} areaData={area} />
              </View>

              <View className='input-group'>
                <View className='input-name'>详细地址</View>
                <Input className='from-input' name='addressInfo' placeholderClass='placeholder_class' placeholder='请填写详细地址'
                  value={areaInfo}
                />
              </View>

            </View>

            <View className='item-group' >
              <View className='input-group input-switch'>
                <View className='input-name'>设为默认地址</View>
                <Switch color='#00a0e9' name='defaultAddress' checked={isDefaultAddress} onClick={this.changeDefaultAddress.bind(this)} />
              </View>
            </View>
          </View>
          <Button className='btn-line-submit' formType="submit">保存</Button>
        </Form>

        <View className='btn-delete' onClick={this.removeUserAddress.bind(this,editId)}>删除地址</View>

      </View>
    )
  }
}

export default AddressEdit
